package com.drore.logapp.http;

import android.util.Base64;


import com.drore.app.utils.LogUtils;
import com.drore.logapp.http.converter.StringConverterFactory;
import com.drore.logapp.http.interceptor.HttpInterceptor;
import com.drore.logapp.http.interceptor.SaveCookiesInterceptor;
import com.drore.logapp.utils.GlobalConfig;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;


/**
 * Created by xiangl
 * on 2018/4/24 0024 下午 3:03
 * description :
 */

public class HttpCookieLogin {
    private static HttpApi baseHttpApi;
    private static OkHttpClient client;
    private static String TAG = "HttpCookieLogin";

    public static HttpApi createHttpClient(final String username, final String password) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder()
                        .header("Authorization", getHeader(username, password))
                        .header("Accept", "application/json")
                        .method(original.method(), original.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
        client = httpClient.addInterceptor(new HttpInterceptor())
                .readTimeout(15, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS)
                .addInterceptor(new SaveCookiesInterceptor()).build();
        baseHttpApi = new Retrofit
                .Builder()
                .client(client)
                .baseUrl(GlobalConfig.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .build()
                .create(HttpApi.class);
        return baseHttpApi;
    }

    /**
     * 构造Basic Auth认证头信息
     *
     * @return
     */
    private static String getHeader(String username, String password) {
        String credentials = username + ":" + password;
        final String basic =
                "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
//        String authHeader = "Basic " + new String(basic);
        String authHeader = basic;
        LogUtils.e("HttpLogin--authHeader=", authHeader);
        return authHeader;
    }
}
